/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bgu.sonar.util.async;

/**
 *
 * @author bennyl
 */
public abstract class ChainedAsyncTask<V, T> extends AsyncTask<T> implements Callback<V> {

    private FutureResult<V> chainFor = null;

    public V chainedResult() {
        return chainFor.getResult();
    }

    public void setChainFor(FutureResult<V> chainFor) {
        this.chainFor = chainFor;
    }

    @Override
    public void onFailed(Exception ex, boolean interrupted) {
        if (chainFor.isCanceled()) {
            super.cancel();
        } else {
            super.result.failed(ex);
        }
    }

    @Override
    public void onSuccess(V res) {
        run();
    }

    @Override
    public T awaitTermination() throws InterruptedException {
        chainFor.awaitResult();
        return super.awaitTermination();
    }

    @Override
    public void cancel() {
        chainFor.cancel();
        super.cancel();
    }
}
